﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WeChatParking.Web.Controllers
{
    public class H5Controller : BaseController
    {
        private bool IsDebugMode
        {
            get
            {
#if DEBUG
                return true;
#endif
                //return false;

                return string.Equals(DateTime.Now.ToString("mmHHdd"), Request.QueryString["Debug"]);
            }
        }
        public ActionResult Index(string returnUrl, string PayApiKey)
        {
            var userBll = new Core.BLL.Wx_user();
            if (IsDebugMode && base.CurrentUserID == 0)
            {

                var user = userBll.GetWxUserByNickname(Request.QueryString["User"] ?? "Te Fuir");
                base.CurrentUserID = user.id;
                base.CurrentOpenId = user.openid;
            }
            //授权
            if (string.IsNullOrWhiteSpace(base.CurrentOpenId) /*&& base.InitUserFromCookie(id) == false*/)
            {
                return RedirectToAction("WxAuthBase", new { state = 1, returnUrl = Request.Url.ToString() });
            }
            if (!string.IsNullOrWhiteSpace(returnUrl))
                return Redirect(returnUrl);

            //查询出最近的在场的进出场记录
            var bll = new Core.BLL.CarRecord();
            var Car_PlateList = new Core.BLL.Car_Plate().GetCar_Plate(base.CurrentUserID);
            string filter = "";
            if (Car_PlateList != null && Car_PlateList.Count == 0) return RedirectToAction("AddCar");
            ViewBag.list = Car_PlateList;
            foreach (var item in Car_PlateList)
            {
                filter += "'" + item.Car_plate + "',";
            }
            filter = filter.TrimEnd(',');
            string sql = String.IsNullOrWhiteSpace(PayApiKey) ? String.Format("carBrand IN ({0}) AND status=1", filter) : String.Format("carBrand IN ({0}) AND status=1 AND retain3='XCPay'", filter);
            var model = bll.Get(sql, "inTime", true).FirstOrDefault();

            if (model == null)
            {
                ViewBag.PayFee = 0.00m;
                return View(new Entity.CarRecord() { });
            }
            decimal fee = String.IsNullOrWhiteSpace(PayApiKey) ? 0.00m : decimal.Parse(model.retain4);
            if (String.IsNullOrWhiteSpace(PayApiKey)) fee = sendFee(model);

            ViewBag.PayFee = fee;
            ViewBag.PayApiKey = string.IsNullOrWhiteSpace(PayApiKey) ? "" : PayApiKey;
            return View(model);
        }
        private decimal sendFee(Entity.CarRecord model)
        {
            //预支付
            Core.BLL.ServerCode serverbll = new Core.BLL.ServerCode();
            //是否已经下发过计费
            var FeeQuery = serverbll.GetFeeQuery(String.Format(" Guid='{0}' and create_time>='{1}'", model.Guid, DateTime.Now.AddMinutes(-1)));
            if (FeeQuery == null)
            {
                var feeModel = new Entity.Api.FeeQuery()
                {
                    Car_plate = model.carBrand,
                    Time = model.inTime.ToString("yyyyMMddHHmm"),
                    Guid = model.Guid,
                    DeviceClient_code = model.retain2,
                    EnterpriseID = model.Enterprise_ID,
                    CCEnterpriseName = model.Enterprise_Name
                };
                //下发计费查询指令
                serverbll.AddFeeQuery(feeModel);
                string code = "";
                bool isOK = TcpServerController.Send(WeChatParking.Core.TCPServer.SendDatas.zhuDongFeeQuery(feeModel, ref code), code);
                if (isOK)
                    serverbll.UpdateFeeQuery(feeModel.Guid, 2);
                return 0.00M;
            }
            else
            {
                return FeeQuery.Fee;
            }
        }
        [HttpPost]
        public ActionResult FeeQuery(string Guid)
        {
            var model = new Core.BLL.CarRecord().Get(Guid);
            if (model != null)
            {
                return Json(new
                 {
                     Fee = sendFee(model)
                 });
            }
            else
            {

                return Json(new
                {
                    Fee = 0m
                });
            }
        }

        [HttpPost]
        public ActionResult ChooseCar(string ChePai)
        {
            var bll = new Core.BLL.CarRecord();
            string sql = String.Format("carBrand = '{0}' AND status=1", ChePai);
            var model = bll.Get(sql, "inTime", true).FirstOrDefault();
            if (model == null)
            {
                ViewBag.PayFee = 0.00m;
                return Json(null);
            }
            else
            {
                decimal fee = sendFee(model);
                model.Y_fee = fee;
                string json = WeChatParking.Util.Conv.ToJson(model);
                return Json(json);
            }
            // return 
        }
        #region index微信用户
        /// <summary>
        /// 微信静默授权
        /// </summary>
        /// <param name="code"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public ActionResult WxAuthBase(string code, string state, string returnUrl)
        {
            if (string.IsNullOrEmpty(code))
            {
                var url = this.GetWxCodeUrl(true, state ?? string.Empty);
                return Redirect(url);
            }
            else
            {
                var wxToken = GetWxOpenId(code);
                if (wxToken != null && wxToken.errcode == 0 && !string.IsNullOrWhiteSpace(wxToken.openid))
                {
                    base.CurrentOpenId = wxToken.openid;
                    var userBll = new Core.BLL.Wx_user();
                    var user = userBll.GetWxUserByOpenId(wxToken.openid);
                    if (user != null)
                    {
                        //已授权过
                        base.CurrentUserID = user.id;
                        base.OAuthUserType = Entity.Enums.OAuthUserType.Wxfw;
                        base.SetCurrentUserToCookie(state);

                        return RedirectToAction("Index", new { id = state, returnUrl = returnUrl });
                    }
                    else
                    {
                        return RedirectToAction("WxAuth", new { state = state, returnUrl = returnUrl });  //重定向到显性授权
                    }

                }
            }
            return View("WxAuth");
        }
        /// <summary>
        /// 微信显性授权
        /// </summary>
        /// <param name="code"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public ActionResult WxAuth(string code, string state, string returnUrl)
        {
            if (string.IsNullOrEmpty(code))
            {
                var url = this.GetWxCodeUrl(false, state ?? string.Empty);
                return Redirect(url);
            }
            else
            {
                var wxToken = GetWxOpenId(code);
                if (wxToken != null && wxToken.errcode == 0 && !string.IsNullOrWhiteSpace(wxToken.openid))
                {
                    base.CurrentOpenId = wxToken.openid;

                    var userBll = new Core.BLL.Wx_user();
                    var user = userBll.GetWxUserByOpenId(wxToken.openid);
                    if (user != null)
                    {
                        //已授权过
                        base.CurrentUserID = user.id;
                        base.OAuthUserType = Entity.Enums.OAuthUserType.Wxfw;
                        base.SetCurrentUserToCookie(state);
                    }
                    else
                    {
                        var wxUser = GetWxUser(wxToken.access_token, wxToken.openid);
                        userBll.AddWxUser(wxUser);
                    }

                    return RedirectToAction("Index", new { id = state, returnUrl = returnUrl });
                }
            }

            return View();
        }
        [HttpGet]
        public ActionResult BindWx()
        {
            return View();
        }
        [HttpPost]
        public ActionResult BindWx(int enterid, string ShoujiHaoma, string username, int yzm)
        {

            if (string.IsNullOrWhiteSpace(ShoujiHaoma) || string.IsNullOrWhiteSpace(username))
            {
                return Fail("请输入绑定的姓名、手机号");
            }
            if (yzm == 0)
            {
                return Fail("请获取验证码");
            }
            if (GetYZM() == yzm)
            {
                return Fail("");
            }
            else
            {
                return Fail("验证码错误");
            }
        }

        private string GetWxCodeUrl(bool isBase, string state)
        {
            string currentUrl = Request.Url.ToString();

            string getWxCodeFmt = Core.Payment.WeixinPay.WxpayConfig.GetCodeLink; // Prepaid.Core.BLL.SystemConfig.GetConfigValue(Entity.Enums.SystemConfig.WxGetCodeUrlFormat);
            if (isBase)
            {
                getWxCodeFmt = getWxCodeFmt.Replace("scope=snsapi_userinfo", "scope=snsapi_base");  //静默授权
            }

            string wxAppId = WeChatParking.Core.BLL.SystemConfig.GetConfigValue(Entity.Enums.SystemConfig.WxAppID);

            string redirectUrl = currentUrl; // currentUrl.Substring(0, index) + "WechatAuthLogin";
            string getWechatCodeUrl = string.Format(getWxCodeFmt, wxAppId, Server.UrlEncode(redirectUrl), state);

            return getWechatCodeUrl;
        }

        private Core.Payment.WeixinPay.WxPayUserAccessToken GetWxOpenId(string code)
        {
            try
            {
                string getWxOpenIdFmt = WeChatParking.Core.BLL.SystemConfig.GetConfigValue(Entity.Enums.SystemConfig.WxGetOpenIDUrlFormat);
                string wxAppId = WeChatParking.Core.BLL.SystemConfig.GetConfigValue(Entity.Enums.SystemConfig.WxAppID);
                string wxAppSecret = WeChatParking.Core.BLL.SystemConfig.GetConfigValue(Entity.Enums.SystemConfig.WxAppSecret);

                string openidLink = string.Format(getWxOpenIdFmt, wxAppId, wxAppSecret, code);
                string rspJson = Util.HttpUtil.DoPost(openidLink, string.Empty);

                var log = new Entity.log();
                log.api_name = "获取openid";
                log.api_url = string.Empty;
                log.log_date = DateTime.Now;
                log.pay_type = 1;
                log.request = openidLink;
                log.response = rspJson;
                Core.LogHelper.Debug(log);

                var token = Util.Conv.ParseJson<Core.Payment.WeixinPay.WxPayUserAccessToken>(rspJson);
                return token;
            }
            catch (Exception ex)
            {
                Core.LogHelper.Error(ex, "获取openid");
                return null;
            }

        }

        private Core.Payment.WeixinPay.WxUserInfo GetWxUser(string access, string openid)
        {
            try
            {
                var getUserFmt = WeChatParking.Core.BLL.SystemConfig.GetConfigValue(Entity.Enums.SystemConfig.WxGetUserInfoUrlFormat);

                string getUserUrl = string.Format(getUserFmt, access, openid);
                string rspJson = Util.HttpUtil.DoPost(getUserUrl, string.Empty);

                var log = new Entity.log();
                log.api_name = "获取用户信息";
                log.api_url = "";
                log.log_date = DateTime.Now;
                log.pay_type = 1;
                log.request = getUserUrl;
                log.response = rspJson;
                Core.LogHelper.Debug(log);

                var user = Util.Conv.ParseJson<Core.Payment.WeixinPay.WxUserInfo>(rspJson);
                return user;

            }
            catch (Exception ex)
            {
                Core.LogHelper.Error(ex, "获取用户信息");
                return null;
            }
        }

        #endregion
        #region user微信用户
        /// <summary>
        /// 微信静默授权
        /// </summary>
        /// <param name="code"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public ActionResult WxAuthBaseUser(string code, string state, string returnUrl)
        {
            if (string.IsNullOrEmpty(code))
            {
                var url = this.GetWxCodeUrl(true, state ?? string.Empty);
                return Redirect(url);
            }
            else
            {
                var wxToken = GetWxOpenId(code);
                if (wxToken != null && wxToken.errcode == 0 && !string.IsNullOrWhiteSpace(wxToken.openid))
                {
                    base.CurrentOpenId = wxToken.openid;
                    var userBll = new Core.BLL.Wx_user();
                    var user = userBll.GetWxUserByOpenId(wxToken.openid);
                    if (user != null)
                    {
                        //已授权过
                        base.CurrentUserID = user.id;
                        base.OAuthUserType = Entity.Enums.OAuthUserType.Wxfw;
                        base.SetCurrentUserToCookie(state);

                        return RedirectToAction("user", new { id = state, returnUrl = returnUrl });
                    }
                    else
                    {
                        return RedirectToAction("WxAuthUser", new { state = state, returnUrl = returnUrl });  //重定向到显性授权
                    }

                }
            }
            return View("WxAuthUser");
        }
        /// <summary>
        /// 微信显性授权
        /// </summary>
        /// <param name="code"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public ActionResult WxAuthUser(string code, string state, string returnUrl)
        {
            if (string.IsNullOrEmpty(code))
            {
                var url = this.GetWxCodeUrl(false, state ?? string.Empty);
                return Redirect(url);
            }
            else
            {
                var wxToken = GetWxOpenId(code);
                if (wxToken != null && wxToken.errcode == 0 && !string.IsNullOrWhiteSpace(wxToken.openid))
                {
                    base.CurrentOpenId = wxToken.openid;

                    var userBll = new Core.BLL.Wx_user();
                    var user = userBll.GetWxUserByOpenId(wxToken.openid);
                    if (user != null)
                    {
                        //已授权过
                        base.CurrentUserID = user.id;
                        base.OAuthUserType = Entity.Enums.OAuthUserType.Wxfw;
                        base.SetCurrentUserToCookie(state);
                    }
                    else
                    {
                        var wxUser = GetWxUser(wxToken.access_token, wxToken.openid);
                        userBll.AddWxUser(wxUser);
                    }

                    return RedirectToAction("user", new { id = state, returnUrl = returnUrl });
                }
            }

            return View();
        }
        #endregion
        /// <summary>
        /// 支付
        /// </summary>
        /// <param name="carReID"></param>
        /// <param name="payval"></param>
        /// <param name="PayApiKey"></param>
        /// <returns></returns>
        public ActionResult SubmitPay(int carReID, decimal payval, string PayApiKey)
        {
            if (carReID <= 0)
            {
                return Fail("无进场记录");
            }
            if (payval < 0.01M)
            {
                return Fail("缴费金额有误");
            }
            if (payval > 999M)
            {
                return Fail("缴费金额太大");
            }
            var orderBll = new Core.BLL.PrepaidOrder();
            var order = orderBll.CreateOrder(base.CurrentUserID, carReID, payval, string.IsNullOrWhiteSpace(PayApiKey) ? "" : PayApiKey);
            if (order == null)
            {
                return Fail("订单创建失败");
            }
            Core.LogHelper.Info(Util.Conv.ToJson(order), Entity.Enums.LogType.CreateOrder);

            return base.OK(order.order_id);
        }

        public ActionResult user(string returnUrl)
        {
            try
            {
                Core.BLL.Wx_user userService = new Core.BLL.Wx_user();
                var dll = new Core.BLL.CarRecord();
                if (IsDebugMode && base.CurrentUserID == 0)
                {
                    var user = userService.GetWxUserByNickname(Request.QueryString["User"] ?? "Te Fuir");
                    base.CurrentUserID = user.id;
                    base.CurrentOpenId = user.openid;
                    ViewBag.list = new Core.BLL.Car_Plate().GetCar_Plate(user.id);
                    return View(user);
                }
                if (string.IsNullOrWhiteSpace(base.CurrentOpenId) /*&& base.InitUserFromCookie(id) == false*/)
                {
                    return RedirectToAction("WxAuthBaseUser", new { state = 1, returnUrl = returnUrl });
                }
                var Car_PlateList = new Core.BLL.Car_Plate().GetCar_Plate(base.CurrentUserID);
                if (Car_PlateList != null && Car_PlateList.Count == 0) return RedirectToAction("AddCar");
                ViewBag.list = Car_PlateList;
                return View(userService.GetWxUserById(base.CurrentUserID));
            }
            catch (Exception e)
            {
                return Fail(e.ToString());
            }
        }

        public ActionResult userCarRecord()
        {
            int userId = base.CurrentUserID;

            var dll = new Core.BLL.CarRecord();
            var Car_Plate = new Core.BLL.Car_Plate().GetCar_Plate(userId);
            string filter = "";
            if (Car_Plate.Count == 0) return RedirectToAction("AddCar");
            foreach (var item in Car_Plate)
            {
                filter += "'" + item.Car_plate + "',";
            }
            filter = filter.TrimEnd(',');
            List<WeChatParking.Entity.CarRecord> list = dll.Get(String.Format("carBrand IN ({0})", filter), "inTime", true);

            ViewBag.list = (from a in list orderby a.inTime descending select a).Take(20).ToList(); ;
            //2、查询出用户查询出近20条数据
            return View();
        }

        #region 添加车牌
        public ActionResult AddCar()
        {
            if (string.IsNullOrWhiteSpace(base.CurrentOpenId) /*&& base.InitUserFromCookie(id) == false*/)
            {
                return RedirectToAction("WxAuthBaseUser", new { state = 1, returnUrl = "" });
            }
            return View();
        }
        [HttpPost]
        public ActionResult AddCar(string ChePai)
        {
            try
            {
                if (ChePai.Length == 0)
                    return base.Fail("车牌不能为空");
                //if (string.IsNullOrWhiteSpace(base.CurrentOpenId) /*&& base.InitUserFromCookie(id) == false*/)
                //{
                //    return RedirectToAction("WxAuthBase", new { state = 1, returnUrl = "" });
                //}
                Core.BLL.Wx_user userService = new Core.BLL.Wx_user();
                var user = userService.GetWxUserById(base.CurrentUserID);

                int NewID = new Core.BLL.Car_Plate().AddCar_Plate(new Entity.Car_Plate() { Wx_userId = user.id, Wxuser_name = user.nickname, Car_plate = ChePai, signNo = "", status = 10, statusDescription = 10 });
                if (NewID <= 0)
                    return base.Fail("车牌已被绑定");
                return base.OK();
            }
            catch (Exception e)
            {
                Core.LogHelper.Error(e, "添加车牌");
                return base.Fail("异常");
            }
        }
        [HttpPost]
        public ActionResult RelieveCar(string ChePai)
        {
            if (ChePai.Length == 0)
                return base.Fail("车牌不能为空");
            if (new Core.BLL.Car_Plate().Delete(ChePai))
            {
                return base.OK();
            }
            else
            {
                return base.Fail("解除绑定失败");
            }
        }
        #endregion

        #region 代缴费
        public ActionResult DaiJiao()
        {
            if (string.IsNullOrWhiteSpace(base.CurrentOpenId) /*&& base.InitUserFromCookie(id) == false*/)
            {
                return RedirectToAction("WxAuthBase", new { state = 1, returnUrl = "" });
            }
            return View();
        }

        [HttpPost]
        public ActionResult DaiJiao(string ChePai)
        {
            if (String.IsNullOrWhiteSpace(ChePai)) return base.Fail("车牌不能是空");
            //查找进出记录
            var bll = new Core.BLL.CarRecord();
            Entity.CarRecord model = bll.Get(String.Format("carBrand IN ('{0}') AND status=1", ChePai), "inTime", true).FirstOrDefault();
            if (model == null) return base.Fail("未查到进出记录");
            return base.OK();
        }

        public ActionResult JiaoFee(string ChePai)
        {
            Entity.CarRecord model = new Core.BLL.CarRecord().Get(String.Format("carBrand IN ('{0}') AND status=1", ChePai), "inTime", true).FirstOrDefault();
            //费用计算
            var feeBll = new Core.BLL.Fee_cfg();
            var entBll = new Core.BLL.Enterprise();
            var ent = entBll.Get(model.Enterprise_ID);
            decimal fee = sendFee(model);
            ViewBag.PayFee = fee;
            return View(model);
        }
        #endregion

    }
}
